package com.xyy.saas.payment.controller;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xyy.saas.payment.dao.mapper.BankBillJd0028Mapper;
import com.xyy.saas.payment.dao.model.*;
import com.xyy.saas.payment.pojo.dto.QueryReconciliationFileDto;
import com.xyy.saas.payment.rpc.EcOrderRemote;
import com.xyy.saas.payment.service.JDPayService;
import com.xyy.saas.payment.service.PinganLoanService;
import com.xyy.saas.payment.service.jd.JDBillService;
import com.xyy.saas.payment.service.job.BalanceMonitorService;
import com.xyy.saas.payment.service.job.impl.DownloadTradeBillService;
import com.xyy.saas.payment.service.job.impl.PinganTradeCheckBillService;
import com.xyy.saas.payment.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/qingtan/test")
public class QingtanTestController {
    @Autowired
    private JDPayService jdPayService;
    @Autowired
    private DownloadTradeBillService downloadTradeBillService;
    @Autowired
    private PinganTradeCheckBillService pinganTradeCheckBillService;
    @Autowired
    private BalanceMonitorService balanceMonitorService;
    @Autowired
    private PinganLoanService pinganLoanService;

    @Autowired
    private BankBillJd0028Mapper bankBillJd0028Mapper;
    @Autowired
    private EcOrderRemote ecOrderRemote;
    @Resource(name = "jDBillServiceImpl0026")
    private JDBillService jDBillServiceImpl0026;
    @Resource(name = "jDBillServiceImpl0028")
    private JDBillService jDBillServiceImpl0028;
    @Resource(name = "jDBillServiceImpl0001")
    private JDBillService jDBillServiceImpl0001;

    @PostMapping("/jD0001DownAndAnalysisBill")
    public String jD0001DownAndAnalysisBill(String date) {
        try {
            log.info("jD0001DownAndAnalysisBill param:{}", date);
            String logPrefix = "jD0001DownAndAnalysisBillApi";
            jDBillServiceImpl0001.downAndAnalysisBill(logPrefix, date);
        } catch (Exception e) {
            log.error("jD0001DownAndAnalysisBill error, {}", date, e);
            return "error";
        }
        return "success";
    }

    /**
     * 京东对账文件缺失数据check
     */
    @PostMapping("/checkJdBill0026")
    public String checkJdBill0026(String date) {
        try {
            String msg = jDBillServiceImpl0026.checkBill(date);
            return msg;
        } catch (Exception e) {
            log.error("checkJdBill0026 error", e);
            return "error";
        }
    }

    /**
     * 京东对账文件缺失数据check
     */
    @PostMapping("/checkJdBill0028")
    public String checkJdBill0028(String date) {
        try {
            String msg = jDBillServiceImpl0028.checkBill(date);
            return msg;
        } catch (Exception e) {
            log.error("checkJdBill0028 error", e);
            return "error";
        }
    }

    /**
     * 补充京东交易对账文件信息
     */
    @PostMapping("/fillJdBill0028")
    public String fillJdBill0028(@RequestBody List<String> payNos) {
        if (CollectionUtils.isEmpty(payNos)) {
            return "param error";
        }

        try {
            List<BankBillJd0028> jd0028List = bankBillJd0028Mapper.queryByPayNos(payNos);
            if (CollectionUtils.isEmpty(jd0028List)) {
                return "jd0028List isEmpty";
            }
            List<BankBillJd0028> targetBills = jd0028List.stream()
                    .filter(bill -> StringUtils.isBlank(bill.getReceiveId()) || StringUtils.isBlank(bill.getReceiveName()) ||
                            StringUtils.isBlank(bill.getUserName()) || StringUtils.isBlank(bill.getYbmOrderNo()))
                    .collect(Collectors.toList());
            if (CollectionUtils.isEmpty(targetBills)) {
                return "targetBills isEmpty";
            }

            List<String> targetPayNos = targetBills.stream().map(BankBillJd0028::getOrderNo).distinct().collect(Collectors.toList());

            Map<String, PayFinanceRefundPlan> payFinanceRefundPlanMap;
            try {
                payFinanceRefundPlanMap = ecOrderRemote.queryListByPayNoMapV2(targetPayNos);
                log.info("payFinanceRefundPlanMap:{}", JSON.toJSONString(payFinanceRefundPlanMap));
            } catch (Exception e) {
                log.error("fillJdBill0028 查ec信息异常, params:{}", JSON.toJSONString(targetPayNos), e);
                return "ecOrderRemote error";
            }

            if (CollUtil.isEmpty(payFinanceRefundPlanMap)) {
                return "payFinanceRefundPlanMap is empty";
            }

            // 填充数据
            List<BankBillJd0028> toUpdateBills = new ArrayList<>();
            for (BankBillJd0028 targetBill : targetBills) {
                PayFinanceRefundPlan payFinanceRefundPlan = payFinanceRefundPlanMap.get(targetBill.getOrderNo());
                if (payFinanceRefundPlan == null) {
                    log.error("fillJdBill0028 payFinanceRefundPlan is null, payNo:{}", targetBill.getOrderNo());
                    continue;
                }

                BankBillJd0028 toUpdateBill = new BankBillJd0028();
                boolean needUpdate = false;

                toUpdateBill.setId(targetBill.getId());
                if (StringUtils.isBlank(targetBill.getReceiveId())) {
                    toUpdateBill.setReceiveId(payFinanceRefundPlan.getBusinessReceiverId());
                    needUpdate = true;
                }
                if (StringUtils.isBlank(targetBill.getReceiveName())) {
                    toUpdateBill.setReceiveName(payFinanceRefundPlan.getReceiverName());
                    needUpdate = true;
                }
                if (StringUtils.isBlank(targetBill.getUserName())) {
                    toUpdateBill.setUserName(payFinanceRefundPlan.getPayerName());
                    needUpdate = true;
                }
                if (StringUtils.isBlank(targetBill.getYbmOrderNo())) {
                    toUpdateBill.setYbmOrderNo(payFinanceRefundPlan.getBusinessPayNo());
                    needUpdate = true;
                }

                if (needUpdate) {
                    toUpdateBills.add(toUpdateBill);
                }
            }

            if (CollectionUtils.isEmpty(toUpdateBills)) {
                return "toUpdateBills is empty";
            }

            int updateds = bankBillJd0028Mapper.updateBatch(toUpdateBills);
            log.info("fillJdBill0028 updateds:{}", updateds);

            return "update done, updateds:" + updateds;
        } catch (Exception e) {
            log.error("fillJdBill0028 error, params:{}", JSON.toJSONString(payNos), e);
            return "error";
        }
    }

    @RequestMapping(value = {"/downloadWeChatBill"})
    public String downloadWeChatBill(String merchantNo, String date) {
        downloadTradeBillService.download(merchantNo, date);
        return "ok";
    }

    @RequestMapping(value = {"/downloadPinganTradeCheckBill"})
    public String downloadPinganTradeCheckBill(String dateFrom, String dateTo, String tradeType, boolean reimport) {
        new Thread(() -> {
            try {
                Date fromDate = DateUtil.parase(dateFrom, DateUtil.DATEFORMATDAY_2);
                Date toDate = DateUtil.parase(dateTo, DateUtil.DATEFORMATDAY_2);
                Date date = fromDate;
                while (true) {
                    if (date.after(toDate)) {
                        break;
                    }
                    if (StringUtils.isBlank(tradeType)) {
                        pinganTradeCheckBillService.download(date, reimport);
                    } else {
                        if (tradeType.equals("CLEAR")) {
                            pinganTradeCheckBillService.downloadDailyClearDataByFileDate(date, reimport);
                        } else {
                            pinganTradeCheckBillService.download(QueryReconciliationFileDto.builder().fileDate(date).fileType(tradeType).build(), reimport);
                        }
                    }
                    date = DateUtil.getNextDay(date);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }).start();

        return "ok";
    }

    @RequestMapping(value = {"/sendBalanceInfoToQiyeWx"})
    public String sendBalanceInfoToQiyeWx() {
        balanceMonitorService.sendBalanceInfoToQiyeWx();
        return "ok";
    }

    @RequestMapping(value = "/sendOpenAccountStatusToQiyeWx")
    public String sendOpenAccountStatusToQiyeWx() {
        balanceMonitorService.sendOpenAccountStatusToQiyeWx();
        return "SUCCESS";
    }

    @RequestMapping(value = "/downloadLoanHuanKuanFile")
    public String downloadLoanHuanKuanFile(String fileDate) {
        pinganLoanService.downloadLoanHuanKuanFile(fileDate, false);
        return "SUCCESS";
    }

    @GetMapping(value = "/export_0026")
    public void export0026Test(HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {
        BankBillJd0026QueryParam param = BankBillJd0026QueryParam.builder().merchantNo("133400097005").settleFinishTimeStart(DateUtil.getDayOffset(DateUtil.DATEFORMATDAY, new Date(), -31)).settleFinishTimeEnd(DateUtil.format(new Date(), DateUtil.DATEFORMATDAY)).build();
        log.info("导出0026对账单数据:{}", JSONObject.toJSONString(param));
        jdPayService.export0026(param, request, response);
    }

    @GetMapping(value = "/export_0027")
    public void export0027(HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {
        BankBillJd0027QueryParam param = BankBillJd0027QueryParam.builder().merchantNo("133400097004").settleFinishTimeStart(DateUtil.getDayOffset(DateUtil.DATEFORMATDAY, new Date(), -31)).settleFinishTimeEnd(DateUtil.format(new Date(), DateUtil.DATEFORMATDAY)).build();
        log.info("导出0027对账单数据:{}", JSONObject.toJSONString(param));
        jdPayService.export0027(param, request, response);
    }

    @GetMapping(value = "/export_0028")
    public void export0028Test(HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {
        BankBillJd0028QueryParam param = BankBillJd0028QueryParam.builder().merchantNo("133400097005").dealTimeStart(DateUtil.getDayOffset(DateUtil.DATEFORMATDAY, new Date(), -31)).dealTimeEnd(DateUtil.format(new Date(), DateUtil.DATEFORMATDAY)).build();
        log.info("导出0028对账单数据:{}", JSONObject.toJSONString(param));
        jdPayService.export0028(param, request, response);
    }

}
